<template>
  <a-modal
    :width="800"
    title="详情"
    :visible.sync="editModalVisible"
    @cancel="handleCancleDbSync"
  >
    <template slot="footer">
      <a-button @click="handleCancleDbSync">
        关闭
      </a-button>
    </template>
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <!-- <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button>批量操作<a-icon type="down" /></a-button>
      </a-dropdown> -->
    </div>
    <a-table
      size="middle"
      bordered
      :rowKey="(record, index) => index"
      :columns="columns"
      :data-source="tableSource"
      :pagination="false"
      :loading="loading"
      :scroll="{y: 300 }"
    >
      <template slot="record" slot-scope="text, record">
        <a-textarea
          v-if="record.editable"
          :value="text"
          @change="e => handleChange(e.target.value, 'record', record)"
        />
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="comments" slot-scope="text, record">
        <a-textarea
          v-if="record.editable"
          :value="text"
          @change="e => handleChange(e.target.value, 'comments', record)"
        />
        <template v-else>
          {{ text }}
        </template>
      </template>
      <template slot="action" slot-scope="text, record">
        <span v-if="record.editable">
          <a @click="() => save(record)">保存</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定取消保存?" @confirm="() => handleCancel(record)">
            <a>取消</a>
          </a-popconfirm>
        </span>
        <span v-else>
          <a v-if="record.dataType === 6" @click="handleEdit(record)">编辑</a>
          <a-divider v-if="record.dataType === 6" type="vertical" />
          <a-popconfirm v-if="record.dataType === 6" title="确定删除吗?" @confirm="() => handleDelete(record)">
            <a>删除</a>
          </a-popconfirm>
          <a v-else @click="handleJump(record)">办理</a>
        </span>
      </template>
    </a-table>
  </a-modal>
</template>
<script>
import { saveBacklog, deleteBacklog, queryBacklogList } from '@/api/backlog'
import moment from 'moment'
import { mapState } from 'vuex'
export default {
  name: 'pendingWorkModal',
  props: {
    calendarValue: {
      type: Object
    }
  },
  computed: {
    ...mapState({
      username: state => state.user.username
    })
  },
  watch: {
    calendarValue: {
      handler(newVal) {
        !this.loading && this.init()
      },
      deep: true
    }
  },
  data() {
    return {
      editModalVisible: false,
      loading: true,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '待办事项',
          align: 'center',
          dataIndex: 'record',
          width: '20%',
          scopedSlots: { customRender: 'record' }
        },
        {
          title: '计划完成时间',
          align: 'center',
          dataIndex: 'planTime',
          scopedSlots: { customRender: 'planTime' }
        },
        {
          title: '待办类别',
          align: 'center',
          dataIndex: 'dataType',
          customRender: function(t, r, index) {
            let text
            switch (t) {
              case 1:
                text = '客户关系维护'
                break
              case 2:
                text = '销售进度'
                break
              case 3:
                text = '信息获知'
                break
              case 4:
                text = '客户关系图'
                break
              case 5:
                text = '不满足项目'
                break
              case 6:
                text = '自定义待办'
                break
              default:
            }
            return text
          }
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'comments',
          width: '20%',
          scopedSlots: { customRender: 'comments' }
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'action',
          width: '20%',
          scopedSlots: { customRender: 'action' }
        }
      ],
      tableSource: [],
      cacheData: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() { // 初始化 获取待办事项
      console.log('-----------------------------')
      this.loading = true
      queryBacklogList({
        time: moment(this.calendarValue).format('YYYY-MM-DD'),
        userId: this.username
      }).then(res => {
        console.log(res)
        if (res.success) {
          console.log(res)
          this.tableSource = res.result
          this.setDataKey()
          this.loading = false
        }
      })
    },
    setDataKey() {
      this.tableSource.forEach((item, i) => {
        item.key = i + 1
        !item.editable ? item.editable = false : ''
      })
      console.log(this.tableSource)
      this.cacheData = JSON.parse(JSON.stringify(this.tableSource))
      return this.tableSource
    },
    handleCancleDbSync() {
      this.editModalVisible = false
    },
    handleAdd() {
      this.tableSource.push({
        dataType: 6,
        editable: true,
        planTime: moment(this.calendarValue).format('YYYY-MM-DD'),
        key: this.tableSource.length + 1
      })
    },
    handleCancel(record) {
      if (record.id) {
        const newData = [...this.tableSource]
        const target = newData.filter(item => record.key === item.key)[0]
        if (target) {
          Object.assign(target, this.cacheData.filter(item => record.key === item.key)[0])
          target.editable = false
          this.tableSource = newData
        }
      } else {
        this.tableSource.forEach((item, i) => {
          if (item.key === record.key) {
            this.tableSource.splice(i, 1)
            return false
          }
        })
      }
    },
    save(data) { // 保存待办
      const param = JSON.parse(JSON.stringify(data))
      param.planTime = moment(param.planTime).valueOf()
      saveBacklog(param).then(res => {
        if (res.success) {
          const newData = [...this.tableSource]
          const target = newData.filter(item => data.key === item.key)[0]
          if (target) {
            target.id = res.result
            target.editable = false
            this.tableSource = newData
          }
          this.$emit('init')
          this.$message.success('保存成功')
        }
      })
    },
    handleDelete(record) { // 删除待办
      deleteBacklog({
        id: record.id
      }).then(res => {
        if (res.success) {
          this.init()
          this.$emit('init')
          this.$message.success('删除成功')
        }
      })
    },
    handleEdit(record) {
      const newData = [...this.tableSource]
      const target = newData.filter(item => record.key === item.key)[0]
      if (target) {
        target.editable = true
        this.tableSource = newData
      }
    },
    handleChange(value, key, record) {
      record[key] = value
    },
    handleChangeDate(date, dateString, key, record) {
      record[key] = date.valueOf()
    },
    handleJump(record) { // 办理业务
      const dataType = record.dataType
      // dataType：1-客户关系维护、2-销售进度、3-信息获知、4-客户关系图、5-不满足项目
      if (dataType === 1) {
        this.$router.push({ path: '/online/cgformList/0b175864cfe84d9d9c5f80c3a5fd0e8a?id=' + record.id })
      } else if (dataType === 2) {
        this.$router.push({ path: '/online/cgformList/b5d45514094e4570b7bdd73f5566c3a5?id=' + record.id })
      } else if (dataType === 3) {
        this.$router.push({ path: '/online/cgformTreeList/75336ceb836d4c53b640634e36413f47?id=' + record.id })
      } else if (dataType === 4) {
        this.$router.push({ path: '/online/cgformList/f9638fcda306435b997aaf6f23d95c6e?id=' + record.id })
      } else if (dataType === 5) {
        this.$router.push({ path: '/online/cgformList/905ea1a9ddac499ba25dcb0b4a7be36a?id=' + record.id })
      }
    }
  }
}
</script>
<style lang="less">

</style>
